package com.healthcare.client.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthcare.client.pojo.*;
import com.healthcare.client.utils.ApplicationContextUtil;
import com.healthcare.client.utils.Cookietwo;
import com.healthcare.client.vo.FirstLetter;
import com.healthcare.client.vo.FirstLetterList;
import com.healthcare.client.mapper.GroupMapper;
import com.healthcare.client.mapper.LoginlogMapper;
import com.healthcare.client.mapper.ReferralMapper;
import com.healthcare.client.pojo.Group;
import com.healthcare.client.pojo.Loginlog;
import com.healthcare.client.pojo.Referral;
import com.healthcare.client.pojo.User;
import com.healthcare.client.mapper.UserMapper;
import com.healthcare.client.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.healthcare.client.utils.FirstLetterUtil;
import com.healthcare.client.utils.SessionUtils;
import com.healthcare.client.vo.MsgVo;
import com.healthcare.common.constants.ResultCodeEnum;
import com.healthcare.common.exception.KetaiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 新华医院转诊联盟
 * @since 2020-04-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private LoginlogMapper loginlogMapper;
    @Autowired
    private ReferralMapper referralMapper;
    @Autowired
    private GroupMapper groupMapper;


    /**
     * 前台登录方法
     * @param mobile 手机号
     * @param password 密码
     * @return
     */
    @Override
    public User Login(String mobile, String password) {
        // 判断参数是否为空
        if(StringUtils.isEmpty(mobile) || StringUtils.isEmpty(mobile) ){
            return null;
        }
        QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();
        queryWrapperUser.eq("mobile",mobile);
        queryWrapperUser.eq("userpassword",password);
        User user = baseMapper.selectOne(queryWrapperUser);
        if(!StringUtils.isEmpty(user)){
            //当身份为小助手时
            if(user.getIdentity()==0){
                SessionUtils.addSession("admin",user);
            }
            //当身份为医生时
            if(user.getIdentity()==1){
                SessionUtils.addSession("doctor",user);
            }
            // 添加日志信息
            Loginlog loginlog = new Loginlog();
            loginlog.setUsername(user.getUsername());
            loginlog.setAccountType(user.getIdentity());
            loginlog.setLoginResult(0);
            loginlogMapper.insert(loginlog);
        }
        // 如果user返回为空时，则为登录失败
        if(StringUtils.isEmpty(user)){
            throw new KetaiException(ResultCodeEnum.LONGIN_FAILED);
        }
        return user;
    }

    /**
     * 获取当日的会诊和转诊数据
     * @return
     */
    @Override
    public Map<String, Object> getClinicalStageMesage(Integer identity) {
        Map<String, Object> map = new HashMap<>();
        /** 默认值为0 ,如果是医生，则根据当前登录的医生id去查询会诊和转诊信息，如果是小助手则查询所有 */
        Integer idvalue = 0;
        User user = null;
        // 当前台身份认证为 医生时
        if(identity == 1){
            // 获取session得值
           Object object =  SessionUtils.getSessionAttr("doctor");
           // 如果为空 ,则说明登陆信息已过期
           if(object == null){
               throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
           }
           user = (User) object;
           idvalue = user.getId();
        }
        //当前台身份认证为 管理员时
        if(identity ==0){
            // 获取session得值
            Object object =  SessionUtils.getSessionAttr("admin");
            // 如果为空 ,则说明登陆信息已过期
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
        }

        // 查询今天的待分诊信息
        List<Group> groupList = groupMapper.getGroupTodayList(idvalue);
        // 查询今天的待转诊信息
        List<Referral> referralList = referralMapper.getReferralTodayList(idvalue);
        map.put("groupList",groupList.size());
        map.put("referralList",referralList.size());
        return map;
    }


    /**
     * 根据一个包含汉字的字符串数组 返回一个汉字拼音首字母和一个以此首字母为首的汉字数组
     *
     * @param characters 字符串数组
     * @return List<FirstLetterList>
     */
    public static List<FirstLetterList> getFirstLetterList(String[] characters,Integer ids[]) {

        //定义一个对象数组，用来存储这些汉字的首字母和汉字本身
        List<FirstLetter> firstLetters = new ArrayList<>();
        int i=0;
        for (String character : characters) {
            FirstLetter firstLetter = new FirstLetter();
            firstLetter.setCharacters(character);
            //使用 获取汉字首字母工具类 获取汉字首字母
            firstLetter.setFirstLetter(FirstLetterUtil.getFirstLetter(character));
            firstLetter.setId(ids[i]);
            i++;
            firstLetters.add(firstLetter);
        }

        //对数组进行排序，以 A-Z 的顺序
        //字典排序
        firstLetters.sort(new Comparator<FirstLetter>() {
            @Override
            public int compare(FirstLetter o1, FirstLetter o2) {
                char[] chars1 = o1.getFirstLetter().toCharArray();
                char[] chars2 = o2.getFirstLetter().toCharArray();
                int i = 0;
                while (i < chars1.length && i < chars2.length) {
                    if (chars1[i] > chars2[i]) {
                        return 1;
                    } else if (chars1[i] < chars2[i]) {
                        return -1;
                    } else {
                        i++;
                    }
                }
                //o1到头
                if (i == chars1.length) {
                    return -1;
                }
                //o2到头
                if (i == chars2.length) {
                    return 1;
                }
                return 0;
            }
        });

        //定义类似[["firstWord": "7", [{"characters": "7号房的礼物", "firstLetter": "7hfdlw"}]}]的数组
        List<FirstLetterList> firstLetterLists = new ArrayList<>();

        //定义类似 "A": [{"characters": "7号房的礼物", "firstLetter": "7hfdlw"}]}] 的map
        Map<String, List<FirstLetter>> map = new LinkedHashMap<>();

        //把第一个字母相同的对象加到对应 map 的对象数组里
        for (FirstLetter firstLetter : firstLetters) {

            //取第一个字母转为大写
            String first = firstLetter.getFirstLetter().substring(0, 1).toUpperCase();

            //取第一个字母对应的对象数组
            List<FirstLetter> chooseFirstLetterList = map.get(first);

            //判断第一个字母对应的对象数组是否已经存在
            List<FirstLetter> firstLetterList;
            if (chooseFirstLetterList == null || chooseFirstLetterList.size() == 0) {
                firstLetterList = new ArrayList<>();
            } else {
                firstLetterList = map.get(first);
            }
            firstLetterList.add(firstLetter);
            map.put(first, firstLetterList);
        }

        //把 map 的 key 和 value 处理一下，变成对象数组的形式

        for (String in : map.keySet()) {

            FirstLetterList firstLetterList = new FirstLetterList();
            firstLetterList.setFirstWord(in);
            firstLetterList.setFirstLetterList(map.get(in));

            firstLetterLists.add(firstLetterList);
        }


        return firstLetterLists;
    }
    /**
     * 前台通讯录列表方法
     * @return
     */
    @Override
    public Map<String,Object> userList() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("identity",1);
       List<User> list=baseMapper.selectList(queryWrapper);
        String[] array = new String[list.size()];  // 用户名数组
        Integer[] ids = new Integer[list.size()];  // 用户id数组
        for (int i = 0; i <list.size() ; i++) {
            array[i] = list.get(i).getUsername();  // 转换成数组 提取首字母
            ids[i] = list.get(i).getId();  // 用户ID唯一
        }
        //进行首字母定位
        List<FirstLetterList> firstLetterLists = getFirstLetterList(array,ids);

        // 所有数据获取map
        Map<String,Object> map = new HashMap<>();

        map.put("firstLetterList",firstLetterLists);  // 首字母数据

        map.put("list",list);  // 用户表数据

        return map;
    }


    /**
     * 前端通讯列表搜索
     * @param userName
     * @return
     */
    @Override
    public List<User> userListName(String userName) {
        QueryWrapper<User>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("identity",1);  //查询条件只能为普通医生
        if (!StringUtils.isEmpty(userName)){   //  判断传过来的字段是否为空
            queryWrapper.like("username",userName); // 不为空进行模糊查询
        }
        return baseMapper.selectList(queryWrapper);
    }

    /**
     *  获取小助手和医生个人信息
     * @param type 0- 医生 1- 小助手
     * @return
     */
    @Override
    public User getProfile(Integer type) {
        User user = null;
        Object object = null;
        // 为医生时
        if(type == 0){
            // 获取session得值
            object  =  SessionUtils.getSessionAttr("doctor");
            // 如果为空 ,则说明登陆信息已过期
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
        }
        // 为小助手时
        if(type == 1){
            // 获取session得值
            object  =  SessionUtils.getSessionAttr("admin");
            // 如果为空 ,则说明登陆信息已过期
            if(object == null){
                throw new KetaiException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
            }
        }
        user = (User) object;
        return user;
    }


    @Override
    public User userIm(Integer userid) {
        return baseMapper.selectById(userid);
    }

    @Override
    public User userAdmin() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("identity",0);
        queryWrapper.eq("is_deleted",0);
        return baseMapper.selectOne(queryWrapper);
    }


}
